package com.simtop.beefsheepmaching.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.beefsheepmaching.common.ServerResponse;
import com.simtop.beefsheepmaching.common.UserUtil;
import com.simtop.beefsheepmaching.dao.CountDao;
import com.simtop.beefsheepmaching.pojo.IlabUser;
import com.simtop.beefsheepmaching.pojo.User;
import com.simtop.beefsheepmaching.service.JwtLoginService;
import com.simtop.beefsheepmaching.service.UserService;
import com.simtop.beefsheepmaching.util.*;
import com.simtop.beefsheepmaching.util.excel.ExcelUtils;
import com.simtop.beefsheepmaching.vo.UserParamsVo;
import com.simtop.beefsheepmaching.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * 用户模块
 */
@Controller
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    @Autowired
    private UserService userService;

    @Autowired
    private JwtLoginService jwtLoginService;

    @Autowired
    private CountDao countDao;

    @Autowired
    private ExcelUtils excelUtils;

    /**
     * 前台用户注册接口
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(@RequestBody UserVo userVo, HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("接收到的前台参数为："+userVo);
        return userService.register(userVo);
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     * @return
     */
    @RequestMapping(value = "/checkCode",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(String email){
        //根据邮箱获取验证码
        return userService.generateCheckCode(email);
    }

    /**
     * 用户登录 成功后给前台返回一个token,后面需要拿这个token去验证
     * todo 用户类型：ilab用户 2019年9月24日15:34:07
     * 前台传入
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody UserVo userVo, HttpServletResponse response){
        if(userVo.getRoleId()==1||userVo.getRoleId()==3){
            User user = new User();
            //角色id
            user.setRoleId(userVo.getRoleId());
            //登录名
            user.setLoginName(userVo.getLoginName());
            //登陆密码
            user.setPassword(userVo.getPassword());
            return jwtLoginService.login(user);
        }
        User user = new User();
        //角色id
        user.setRoleId(userVo.getRoleId());
        //登录名
        user.setLoginName(userVo.getLoginName());
        //登陆密码
        user.setPassword(userVo.getPassword());
        return jwtLoginService.login(user);
    }

    /**
     * 游客登录
     * @return
     */
    @PostMapping("/tourist")
    @ResponseBody
    public ServerResponse<String> tourist(){
        UserVo loginUser = new UserVo();
        String s = UUID.randomUUID().toString();
        loginUser.setLoginName(s);
        loginUser.setUsername("评审专家");
        loginUser.setRoleId(3);
        loginUser.setSchool("北方民族大学");
        loginUser.setProvince("宁夏回族自治区");
        loginUser.setCity("银川市");
        loginUser.setPassword("BMD_tourist");
        userService.insertBackUser(loginUser);
        User user = new User();
        //角色id
        user.setRoleId(3);
        //登录名
        user.setLoginName(s);
        //登陆密码
        user.setPassword("BMD_tourist");
        return jwtLoginService.login(user);
    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     *
     */
    @RequestMapping(value = "/forget_checkCode",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode( String email){
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(email);
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody UserVo userVo){
        return userService.updatePassword(userVo);
    }

    /**
     * 新增后台用户管理记录
     */
    @RequestMapping(value = "/backend/add",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> addUser(@RequestBody UserVo userVo, Integer userId, HttpServletRequest request){
        return userService.insertBackUser(userVo);
    }

    /**
     * 根据用户id删除User表数据
     */
    @RequestMapping(value = "/deleteByUserId",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> deleteById(@RequestBody String data, HttpServletRequest request){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer userId = jsonObject.getInteger("userId");
        logger.info("管理员删除用户,编号为{}",userId);
        return userService.deleteByUserId(userId);
    }

    /**
     * 修改用户信息
     * @param userVo
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/backend/update",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updateBackendUser(@RequestBody UserVo userVo, HttpServletRequest request){
        return userService.updateBackendUser(userVo);
    }

    /**
     * 根据用户id查询用户信息
     */
    @RequestMapping(value = "/backend/findById",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<User> findUserById(HttpServletRequest request, Integer id){
        return userService.findById(id);
    }

    /**
     * 用户查询功能(学校、姓名、登录名查询)
     */
    @GetMapping(value = "/backend/findByParams")
    @ResponseBody
    public ServerResponse<PageInfo<User>> findByParams(UserParamsVo params,HttpServletRequest request,Integer pageNum,Integer pageSize){
        params.setRoleId(UserUtil.getRoleId(request));
        params.setUserId(UserUtil.getUserId(request));
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userService.findByParams(params);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 获取模板
     */
    @GetMapping("/getUserTemplate")
    public void getUserTemplate(HttpServletRequest request,HttpServletResponse response){
        excelUtils.cooperation(request,response,User.class,"上传用户模板");
    }

    /**
     * 上传接口
     */
    @PostMapping("/importUser")
    @ResponseBody
    public ServerResponse<Object> importUsers(MultipartFile file){
        List<Object> upload = excelUtils.upload(file,User.class);
        return userService.importUsers(upload);
    }
}